package com.th.coupon.common.advice;


import com.th.coupon.common.annotation.IgnoreResponseAdvice;
import com.th.coupon.common.vo.CommonResponse;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * 响应格式的处理器
 * @author 涂航
 */
@RestControllerAdvice
public class CommonResponseDataAdvice implements ResponseBodyAdvice<Object> {

    /**
     * 是否执行处理
     * @param returnType
     * @param converterType
     * @return
     */
    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {

        return !(returnType.getDeclaringClass().isAnnotationPresent(IgnoreResponseAdvice.class)
                || returnType.getMethod().isAnnotationPresent(IgnoreResponseAdvice.class));
    }

    /**
     * 处理的详细逻辑
     * @param body
     * @param returnType
     * @param selectedContentType
     * @param selectedConverterType
     * @param request
     * @param response
     * @return
     */
    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {

        CommonResponse<Object> commonResponse = new CommonResponse(0,"");

        if(body instanceof CommonResponse){
            commonResponse = (CommonResponse) body;
        }else {
            commonResponse.setData(body);
        }

        return commonResponse;
    }
}
